<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\event\AdminActionEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use think\Request;
use app\model\AdminRole;
use app\traits\MyControllerTrait;
use think\facade\Log;
use think\facade\Db;
use app\model\AdminRolePermission;
use app\validate\admin\AdminRoleValidate;
use think\exception\ValidateException;
use think\facade\Session;

class AdminRoleController
{
    use MyControllerTrait;

    protected string $uri = '/admin/role';

    public function index()
    {
        $data = [
            'uri'   => $this->uri,
            'uri2'  => '/admin/role-permission',
            'menus' => $this->getMenuNav($this->uri.'/'.__FUNCTION__),
            'title' => $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
        ];
        return view($this->uri.'/'.__FUNCTION__, $data);
    }// index() end

    public function show(Request $request)
    {
        // admin_role.title
        $title = $request->get('title/s', '');
        $page  = $request->get('page/d', 1);
        $limit = $request->get('limit/d', 10);
        $where = "";
        $raw   = [];
        if (strlen($title) > 0)
        {
            $where       .= " AND title = :title";
            $raw['title'] = $title;
        }

        [$total, $data] = AdminRole::searchForShow(AdminRole::class, $where, $raw, $page, $limit);
        return json(['code' => 0, 'message' => 'success', 'data' => $data, 'total' => $total]);
    }// show() end

    public function create(Request $request)
    {
        $data = [
            'uri'       => $this->uri,
            '__token__' => $request->buildToken()
        ];
        return view($this->uri.'/'.__FUNCTION__, $data);
    }// create() end

    public function store(Request $request)
    {
        $title = $request->post('title/s', '');

        // 验证器校验
        $check_data = ['title' => $title];
        try {
            validate(AdminRoleValidate::class)->check($check_data);
        } catch (ValidateException $validateException) {
            return json(['code' => 0, 'message' => $validateException->getError()]);
        }

        $role = AdminRole::whereRaw('title = :title', ['title' => $title])->findOrEmpty();
        if ($role->isExists()) return json(['code' => 0, 'message' => '角色名称已存在.']);

        if ($request->checkToken('__token__') === false) return json(['code' => 0, 'message' => '页面失效,请刷新页面']);

        AdminRole::generateLog($title);
        $data = [
            $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
            Session::get("admin_user.account"),
            $role->title
        ];
        (new EventDispatcher)->dispatch((new AdminActionEvent($request, $data)), AdminActionEvent::EVENT_NAME);
        return json(['code' => 1, 'message' => '保存成功']);
    }// store() end

    public function edit(Request $request)
    {
        $admin_role_id = $request->get('id/d', 0);
        $admin_role_id = abs($admin_role_id);

        $role = AdminRole::whereRaw('id = :id', ['id' => $admin_role_id])->findOrEmpty();
        if ($role->isEmpty()) return json(['code' => 0, 'message' => '记录不存在']);

        $data = [
            'uri'       => $this->uri,
            'data'      => $role->toArray(),
            '__token__' => $request->buildToken()
        ];
        return view($this->uri.'/'.__FUNCTION__, $data);
    }// edit() end

    public function update(Request $request)
    {
        $admin_role_id = $request->put('id/d', 0);
        $title         = $request->put('title/s', '');

        // 验证器校验
        $check_data = ['title' => $title];
        try {
            validate(AdminRoleValidate::class)->check($check_data);
        } catch (ValidateException $validateException) {
            return json(['code' => 0, 'message' => $validateException->getError()]);
        }

        $role = AdminRole::whereRaw('id = :id', ['id' => $admin_role_id])->findOrEmpty();
        if ($role->isEmpty()) return json(['code' => 0, 'message' => '角色 ID 不存在']);

        $res = AdminRole::whereRaw('title = :title', ['title' => $title])->findOrEmpty();
        if ($res->isExists()) return json(['code' => 0, 'message' => '角色名称已存在']);
        if ($request->checkToken('__token__') === false) return json(['code' => 0, 'message' => '页面失效,请刷新页面']);

        if ($role->title != $title)
        {
            $role->title = $title;
            $role->save();
        }
        $data = [
            $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
            Session::get("admin_user.account"),
            $role->title
        ];
        (new EventDispatcher)->dispatch((new AdminActionEvent($request, $data)), AdminActionEvent::EVENT_NAME);
        return json(['code' => 1, 'message' => '保存成功']);
    }// update() end

    public function destroy(Request $request)
    {
        $admin_role_id = $request->delete('id/d', 0);// admin_role.id

        $role = AdminRole::whereRaw('id = :id', ['id' => $admin_role_id])->findOrEmpty();
        if ($role->isEmpty()) return json(['code' => 0, ' message' => '角色 ID 不存在']);

        Db::startTrans();
        try {
            $role->delete();
            AdminRolePermission::whereRaw('admin_role_id = :admin_role_id', ['admin_role_id' => $admin_role_id])->delete();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $message = [
                'function'  => __CLASS__.'->'.__FUNCTION__.'():'.__LINE__,
                'error'     => $e->getMessage()
            ];
            Log::channel('admin-controller')->error(json_encode($message, JSON_UNESCAPED_UNICODE));
            return json(['code' => 0, 'message' => '删除失败']);
        }

        $data = [
            $this->getPermissionTitle($this->uri.'/'.__FUNCTION__),
            Session::get("admin_user.account"),
            $role->title
        ];
        (new EventDispatcher)->dispatch((new AdminActionEvent($request, $data)), AdminActionEvent::EVENT_NAME);
        return json(['code' => 1, 'message' => '删除成功']);
    }// destroy() end
}
